<template>
  <div class="distribution-channel-list">
    <el-card class="box-card header-box">
      <div class="box-title">
        <span>销售渠道列表</span>
      </div>
      <div class="box-detail">
        <span>
          销售渠道列表，可以修改产品策划页面中销售渠道的一、二级列表选项
        </span>
      </div>
      <div class="search">
        <el-form :inline="true" :model="searchForm" class="demo-form-inline">
          <el-form-item label="一级渠道">
            <el-input
              clearable
              v-model="searchForm.firstName"
              placeholder="一级渠道"
            ></el-input>
          </el-form-item>
          <el-form-item label="二级渠道">
            <el-input
              clearable
              v-model="searchForm.secondName"
              placeholder="二级渠道"
            ></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchSubmit">查询</el-button>
            <el-button type="info">重置</el-button>
            <el-button type="primary" @click="handleFirstCreate"
              >新建</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <el-row :gutter="20">
      <div v-if="distribution_channel.length > 0">
        <div v-for="first in distribution_channel" :key="first.name">
          <el-col :span="spanByWidth">
            <div class="grid-content bg-purple">
              <el-card class="box-card channel-box">
                <div slot="header" class="clearfix channel_header">
                  <span>{{ first.name }}</span>
                  <el-button
                    @click="handleFirstEdit(first)"
                    style="float: right; padding: 3px 0"
                    type="text"
                  >
                    编辑
                  </el-button>
                  <el-button
                    @click="handleSecondCreate(first.id)"
                    style="float: right; margin-right: 6 px; padding: 3px 0"
                    type="text"
                  >
                    添加
                  </el-button>
                </div>
                <el-table :data="first.children" border>
                  <el-table-column prop="name" label="二级渠道">
                  </el-table-column>
                  <el-table-column label="操作">
                    <template slot-scope="scope">
                      <el-button
                        size="small"
                        @click="handleSecondEdit(scope.row)"
                        >编辑</el-button
                      >
                      <el-button
                        type="danger"
                        size="small"
                        @click="handleDelete(scope.row.id)"
                        >删除</el-button
                      >
                    </template>
                  </el-table-column>
                </el-table>
              </el-card>
            </div>
          </el-col>
        </div>
      </div>
      <div v-else>
        <el-empty description="暂无渠道"></el-empty>
      </div>
    </el-row>
    <!-- dialog -->
    <el-dialog title="一级渠道编辑" :visible.sync="dialogFirstChannelVisible">
      <el-form :model="firstForm" :rules="rules" ref="firstForm">
        <el-form-item label="一级渠道名称" prop="name">
          <el-input v-model="firstForm.name" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFirstChannelVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleFirstEditSubmit"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog title="二级渠道编辑" :visible.sync="dialogSecondChannelVisible">
      <el-form :model="secondForm" :rules="rules" prop="name">
        <el-form-item label="二级渠道名称">
          <el-input v-model="secondForm.name" auto-complete="off"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogSecondChannelVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleSecondEditSubmit"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { uploadFileRequest } from "@/api/api";
import Vue from "vue";
import { getRequest } from "@/api/api";
import { postRequest } from "@/api/api";
import { getCookie } from "@/util/common";
import store from "../../../store";
export default {
  data() {
    return {
      winWidth: store.getters.winWidth,
      rules: {
        name: [
          { required: true, message: "请输入渠道名称", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "长度在2到20个字符",
            trigger: "blur",
          },
        ],
      },
      dialogFirstChannelVisible: false,
      dialogSecondChannelVisible: false,
      dialogType: "",
      searchForm: {
        firstName: "",
        secondName: "",
      },
      formInline: {
        user: "",
        region: "",
      },
      newBrand: {
        name: "",
        desc: "",
      },
      fileList: [],
      firstForm: {
        id: "",
        name: "",
        level: "0",
        parentId: "0",
        createId: "",
        description: "暂无",
      },
      secondForm: {
        id: "",
        name: "",
        level: "1",
        parentId: "0",
        createId: "",
        description: "暂无",
      },
      tableData: [],
      distribution_channel: [],
      currentUser: "",
    };
  },
  computed: {
    spanByWidth() {
      if (this.winWidth < 1400) {
        return 12;
      } else {
        return 6;
      }
    },
  },
  mounted() {
    this.loadChannel();
    console.log(this.currentUserId);
    var temp = getCookie("currentUser");
    this.currentUser = JSON.parse(temp);
    // console.log("currentUser", this.currentUser);
    this.firstForm.createId = this.currentUser.id;
    this.secondForm.createId = this.currentUser.id;
  },
  methods: {
    loadChannel() {
      getRequest("/distribution_channel/list", this.searchForm)
        .then((res) => {
          this.distribution_channel = res.data.data;
        })
        .catch((err) => {
          // console.log(err);
        });
    },
    handleDelete(id) {
      this.$confirm(
        "此操作将会删除该渠道，可能会影响到策划文档，是否继续？",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          let params = { id: id };
          postRequest("/distribution_channel/delete", params)
            .then((res) => {
              this.$message.success(res.data.msg);
              this.loadChannel();
            })
            .catch((err) => {
              this.$message.error(err);
            });
        })
        .catch(() => {
          this.$message.error("已取消");
        });
    },
    searchSubmit() {
      log(this.secondForm);
      this.loadChannel();
    },
    handleFirstCreate() {
      this.firstForm.name = "";
      this.firstForm.id = null;
      this.type = "create";
      this.dialogFirstChannelVisible = true;
      this.$nextTick(() => {
        this.$refs.firstForm.clearValidate();
      });
    },
    handleFirstEdit(channel) {
      // console.log(channel);
      this.firstForm.name = channel.name;
      this.firstForm.id = channel.id;
      this.type = "edit";
      this.dialogFirstChannelVisible = true;
      this.$nextTick(() => {
        this.$refs.firstForm.clearValidate();
      });
    },
    handleFirstEditSubmit() {
      // this.distribution_channel[0].name = this.firstForm.name;
      this.$refs["firstForm"].validate((valid) => {
        if (valid) {
          // console.log(this.$refs["firstForm"]);
          alert("success");
          return true;
        } else {
          return false;
        }
      });
      if (this.type == "create") {
        let params = {
          name: this.firstForm.name,
          level: "0",
          parentId: "0",
          createId: this.currentUser.id,
        };
        postRequest("/distribution_channel/insert", params).then((res) => {
          this.loadChannel();
        });
      } else if (this.type == "edit") {
        postRequest("/distribution_channel/update", this.firstForm).then(
          (res) => {
            this.loadChannel();
          }
        );
      }

      this.dialogFirstChannelVisible = false;
    },
    handleSecondCreate(channel) {
      this.dialogType = "create";
      this.dialogSecondChannelVisible = true;
      this.secondForm.name = "";
      this.secondForm.parentId = channel;
      // console.log(channel);
    },
    handleSecondEdit(channel) {
      this.dialogType = "edit";
      this.dialogSecondChannelVisible = true;
      this.secondForm.id = channel.id;
      this.secondForm.name = channel.name;
      this.secondForm.parentId = channel.parentId;
      this.secondForm.level = channel.level;
    },
    handleSecondEditSubmit() {
      if (this.dialogType == "create") {
        let params = {
          name: this.secondForm.name,
          parentId: this.secondForm.parentId,
          createId: this.currentUser.id,
          level: "1",
        };
        postRequest("/distribution_channel/insert", params).then((res) => {
          if (res.data.code == 1000) {
            this.dialogSecondChannelVisible = false;
            this.loadChannel();
          } else if (res.data.code == 1001) {
            this.$message.error(res.data.msg);
          }
        });
      } else if (this.dialogType == "edit") {
        let params = {
          name: this.secondForm.name,
          id: this.secondForm.id,
          parentId: this.secondForm.parentId,
          level: this.secondForm.level,
        };
        postRequest("/distribution_channel/update", params).then((res) => {
          if (res.data.code == 1000) {
            this.dialogSecondChannelVisible = false;
            this.loadChannel();
          } else if (res.data.code == 1001) {
            this.$message.error(res.data.msg);
          }
        });
      }
    },

    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
  },
};
</script>
<style scoped>
.distribution-channel-list {
  margin: 40px auto;
}
.listTable {
  margin-bottom: 20px;
}
.text {
  font-size: 14px;
}
.search {
  text-align: right;
}
.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.channel_item {
  text-align: left;
  height: 200px;
  overflow: auto;
}
.channel-box >>> .el-card__body {
  overflow: auto;
  height: 80%;
  text-align: left;
  padding-top: 20px;
}
.clearfix:after {
  clear: both;
}

.header-box {
  margin-bottom: 16px;
  padding: 24px;
}
.channel-box {
  height: 600px;
  box-sizing: border-box;
  margin-bottom: 16px;
}
.box-title {
  text-align: left;
  font-size: 20px;
}
.box-detail {
  text-align: left;
  color: gray;
  font-size: 14px;
}
.channel_header {
  text-align: left;
}
.new_channel {
  height: 398px;
  width: 100%;
  border: dashed 1px gray;
}
</style>